﻿Imports System.Data.SqlClient

Public Class Frm_SALIA
    Implements IDServer.IDServer.IDServer

#Region " variable and Property "

    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

    Private WithEvents MainForm As Frm_MainForm
    ''' <summary>
    ''' 用於保存門店和倉庫的代碼的對應關係
    '''egg.|| DeptCode(250) | Dept (YL) |  fShortName (元朗白沙倉)
    ''' </summary> 
    Private DeptTb As DataTable

#End Region

#Region " Interface "

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        If AddEnable = False Then
            MessageBox.Show(My.Resources.NotAllowAdd, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If


        If Me.TabControl1.SelectedIndex = 0 Then
            Me.TabControl1.SelectedIndex = 1
        End If
        Dim iaG As New Frm_IAGoodsSuggest
        iaG.StartPosition = FormStartPosition.CenterParent
        Dim tb As New DataTable
        If iaG.ShowDialog() = DialogResult.OK Then
            tb = iaG.getSelectdata()
            ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
            SetToolEnable()
            Me.tbxRemark.ReadOnly = False
            Me.tbxRemark.Refresh()
            ClearText()
        Else
            Me.MainForm.ToolStripCancel.Enabled = True
            Me.MainForm.ToolStripCancel.PerformClick()
            Return False
        End If



        Dim tab As DataTable = CType(Me.dgvIADetail.DataSource, DataTable)
        tab.Rows.Clear()
        tab.Columns("AMOUNT").Expression = "PRICE*Qty"

        Dim itemcount As Int32 = 1
        '將選中的貨品清單數據填充導DataGridView
        For Each datarow As DataRow In tb.Rows
            If datarow("IsSelected").Equals(True) And Convert.ToInt32(datarow("IAAmount")) > 0 Then
                Dim row As DataRow = tab.NewRow()
                row("SOSEQ_NO") = itemcount  ' 這個選項,表示項數
                row("ITEM_NO") = datarow("Enname")
                row("BarCode") = datarow("BarCode")
                row("SupperItem") = datarow("SupperItem")
                row("Cnname") = datarow("GoodsName")
                row("WHFROM") = Convert.ToInt32(Me.DeptTb.Select("Dept='" + datarow("WHFROM").ToString + "'")(0)("DeptCode"))
                row("WHTO") = Convert.ToInt32(Me.DeptTb.Select("Dept='" + datarow("WHTO").ToString + "'")(0)("DeptCode"))
                row("RECDATE") = Me.dtpRecDate2.Text   'datarow("")
                row("QTY") = datarow("IAAmount")
                row("CURRENCY") = "" 'datarow("")
                row("COST") = 0   'datarow("")
                row("PRICE") = 0  'datarow("")
                ' row("AMOUNT") = 0   ' datarow("")
                tab.Rows.Add(row)
                itemcount = itemcount + 1
            End If
            tab.AcceptChanges()
        Next
        If tb.Rows.Count = 0 Then
            Msg.MsgOK("目的倉沒有需要調撥貨品", "", MessageBoxIcon.Information)
            Me.MainForm.ToolStripCancel.Enabled = True
            Me.MainForm.ToolStripCancel.PerformClick()
        ElseIf tab.Rows.Count = 0 Then
            Msg.MsgOK("原倉庫沒有可以調撥的庫存", "", MessageBoxIcon.Information)
            Me.MainForm.ToolStripCancel.Enabled = True
            Me.MainForm.ToolStripCancel.PerformClick()
        End If
        Me.dgvIADetail.DataSource = tab
        Return True
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
        Me.SetToolEnable()
        dgvIAMaster_CurrentCellChanged(Me.dgvIAMaster, Nothing)
        Return True
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete
        If DeleteEnable = False Then
            MessageBox.Show("對不起，您沒有刪除的權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If
        If Me.dgvIAMaster.CurrentCell Is Nothing Then
            Exit Function
        End If
        Dim index As Int32 = Me.dgvIAMaster.CurrentCell.RowIndex
        Dim IANum As String = Me.dgvIAMaster.Rows(index).Cells("VOUCHER_NO").Value.ToString
        If Msg.MsgOKCancel(My.Resources.ConfirmDelete + vbNewLine + "IA單號：" + IANum, Msg.CompanyName, MessageBoxDefaultButton.Button1) <> DialogResult.OK Then Return False

        Dim SQLStr As String = String.Empty
        SQLStr += "delete from Sal_IAA where VOUCHER_NO='{0}'" + vbNewLine
        SQLStr += "delete from Sal_IAB where VOUCHER_NO='{0}'" + vbNewLine
        Dim sql As String = String.Format(SQLStr, IANum)
        Try
            Dim val As Object = Exec(sql, E_ExecType.ExecuteNonQuery, True)
            Me.dgvIAMaster.Rows.RemoveAt(index)
        Catch ex As Exception
            Msg.MsgError("刪除失敗")
        End Try
    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        Try
            If App.ExportEnable = False Then
                MessageBox.Show(My.Resources.NotAllowExport, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
                SaveXls(CType(Me.dgvIAMaster.DataSource, DataTable))
            End If
        Catch ex As Exception
            MessageBox.Show(Msg.CompanyName, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        Dim succed As Boolean = False
        Dim dtt As New DataTable

        Dim dt As DataTable = CType(Me.dgvIADetail.DataSource, DataTable)
        If dt Is Nothing Or dt.Rows.Count = 0 Then
            ''設置按鈕 然後退出
            Msg.MsgError("沒有數據可以保存")
            Exit Function
        End If
        dt.AcceptChanges()
        Dim dt2 As DataTable = dt.Copy()
        If Not dt2.Columns.Contains("BINFROM") Then
            dt2.Columns.Add("BINFROM", GetType(Int32), "0")
        End If
        If Not dt2.Columns.Contains("BINTO") Then
            dt2.Columns.Add("BINTO", GetType(Int16), "0")
        End If
        dt2.Columns.Add("VOUCHER_NO", GetType(String))
        'dt2.Columns.Add("ITEM_NO", GetType(String))
        'dt2.Columns.Add("SOSEQ_NO", GetType(Int16))
        'dt2.Columns.Add("WHFROM", GetType(Int16))
        'dt2.Columns.Add("WHTO", GetType(Int16))
        'dt2.Columns.Add("BINFROM", GetType(String))
        'dt2.Columns.Add("BINTO", GetType(String))
        'dt2.Columns.Add("RECDATE", GetType(DateTime))
        'dt2.Columns.Add("QTY", GetType(Decimal))
        'dt2.Columns.Add("CURRENCY", GetType(String))
        'dt2.Columns.Add("COST", GetType(Double))
        'dt2.Columns.Add("PRICE", GetType(Decimal))
        'dt2.Columns.Add("AMOUNT", GetType(Decimal))
        dt2.Columns.Remove("BarCode")
        dt2.Columns.Remove("SupperItem")
        dt2.Columns.Remove("Cnname")
        dt2.AcceptChanges()

        Dim TOTAL_COST As Double = 0.0
        Dim AMOUNT As Double = 0.0


        For Each drowa As DataRow In dt2.Rows
            TOTAL_COST = TOTAL_COST + (Convert.ToDouble(drowa("Cost"))) * (Convert.ToDouble(drowa("Qty")))
            AMOUNT = AMOUNT + Convert.ToDouble(drowa("AMOUNT"))
        Next

        Dim WHFROM As String = Me.DeptTb.Select("DeptCode='" + dt2.Rows(0)("WHFROM").ToString() + "'")(0)("Dept")
        Dim WHTO As String = Me.DeptTb.Select("DeptCode='" + dt2.Rows(0)("WHTO").ToString() + "'")(0)("Dept")

        Dim mode As String = "10"
        '獲取IA單號，然後再繼續
        Dim bonumsql As String = " exec returnBillNum 'sal_IAA','VOUCHER_NO','IA'"
        Dim bonum As String


        Dim SqlBulk As SqlBulkCopy
        Dim sqlConn As SqlConnection = GetConn()
        If sqlConn.State = ConnectionState.Closed Then
            sqlConn.Open()
        End If
        Dim transqlserver As SqlTransaction = sqlConn.BeginTransaction
        Dim sqlcmd As New SqlCommand
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                With sqlcmd
                    .Connection = sqlConn
                    .Transaction = transqlserver
                    .CommandType = CommandType.Text
                    .CommandText = bonumsql
                End With
                bonum = sqlcmd.ExecuteScalar().ToString

                Dim SQLStr As String = String.Empty
                SQLStr += "INSERT INTO [Sal_IAA] (" + vbNewLine
                SQLStr += "[VOUCHER_NO] ,[MODE] ,[Document_NO] ,[TOTAL_COST] ,[AMOUNT] ,[WHFROM] ," + vbNewLine
                SQLStr += "[WHTO] ,[RecDate],[Operator] ,[OperateDate] ,[CheckedBy] ,[CheckDate] ,[UncheckedBy] ," + vbNewLine
                SQLStr += "[UncheckedDate] ,[Status] ,[REMARK] )" + vbNewLine
                SQLStr += "VALUES ('" + bonum + "','" + mode + "','','" + TOTAL_COST.ToString + "','" + AMOUNT.ToString + "','" + WHFROM + "'," + vbNewLine
                SQLStr += "'" + WHTO + "','" + Me.dtpRecDate2.Text + "','" + App.PubUserName + "',Convert(varchar(10),getdate(),120),null,null," + vbNewLine
                SQLStr += "null,null,'A','" + tbxRemark.Text + "')" + vbNewLine
                With sqlcmd
                    .Connection = sqlConn
                    .Transaction = transqlserver
                    .CommandType = CommandType.Text
                    .CommandText = SQLStr
                    .ExecuteNonQuery()
                End With


                For Each dtrow As DataRow In dt2.Rows
                    dtrow("VOUCHER_NO") = bonum
                Next
                dt2.AcceptChanges()
                dt2.Columns("VOUCHER_NO").SetOrdinal(0)
                dt2.Columns("ITEM_NO").SetOrdinal(1)
                dt2.Columns("SOSEQ_NO").SetOrdinal(2)
                dt2.Columns("WHFROM").SetOrdinal(3)
                dt2.Columns("WHTO").SetOrdinal(4)
                dt2.Columns("BINFROM").SetOrdinal(5)
                dt2.Columns("BINTO").SetOrdinal(6)
                dt2.Columns("RECDATE").SetOrdinal(7)
                dt2.Columns("QTY").SetOrdinal(8)
                dt2.Columns("CURRENCY").SetOrdinal(9)
                dt2.Columns("COST").SetOrdinal(10)
                dt2.Columns("PRICE").SetOrdinal(11)
                dt2.Columns("AMOUNT").SetOrdinal(12)
                dt2.AcceptChanges()
                SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transqlserver)
                SqlBulk.DestinationTableName = "Sal_IAB"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(dt2)

                Dim SQL As String = String.Empty
                SQL += "select  VOUCHER_NO,e.ListB as MODE, d.ListA as Status , Document_NO, TOTAL_COST, AMOUNT, WHFROM, WHTO, Operator," + vbNewLine
                SQL += "RecDate,OperateDate, CheckedBy, CheckDate, UncheckedBy, UncheckedDate, REMARK" + vbNewLine
                SQL += "from  Sal_IAA a left join BSC_OtherDefineB d on a.Status=d.ListCode and d.ItemNo=16" + vbNewLine
                SQL += "left join BSC_OtherDefineB e on e.ItemNo=96 and a.Mode=e.listcode" + vbNewLine
                SQL += "  where 1=1 and Voucher_No='" + bonum + "'" + vbNewLine
                With sqlcmd
                    .Connection = sqlConn
                    .Transaction = transqlserver
                    .CommandType = CommandType.Text
                    .CommandText = SQL
                End With
                Dim dr As SqlDataReader = sqlcmd.ExecuteReader()
                dtt.Load(dr)
                transqlserver.Commit()
                sqlConn.Close()
                succed = True
            End If
        Catch ex As Exception
            transqlserver.Rollback()
            MsgBox("ActionSave:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            SetToolEnable()
        End Try
        If succed = True Then
            InsertToDGV(Me.dgvIAMaster, dtt)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            SetToolEnable()
        End If
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

    Public Function ActionChecked() As Boolean
        If CheckEnable = False Then
            MessageBox.Show("對不起，您沒有審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If
        If Me.dgvIAMaster.CurrentCell Is Nothing Then Return False
        If MessageBox.Show(My.Resources.ComfirmChecked, Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> DialogResult.OK Then Return False
        Dim succed = Me.setBillStatus(E_VouStatus.核准)
        If succed Then
            SetDataGridViewBackColor(Me.dgvIAMaster, "Status")
            Me.prePareCheckToolEnable()
            Msg.MsgOK("審核成功", "", MessageBoxIcon.Information)
        Else
            Msg.MsgError("審核不成功，IA的數量不對，請重新生成新的IA")
        End If
    End Function

    Public Function ActionUnChecked() As Boolean
        If UncheckEnable = False Then
            MessageBox.Show("對不起，您沒有反審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If
        If Me.dgvIAMaster.CurrentCell Is Nothing Then Return False
        If MessageBox.Show(My.resources.ComfirmUnchecked, Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> DialogResult.OK Then Return False
        If Me.setBillStatus(E_VouStatus.反核准) Then
            SetDataGridViewBackColor(Me.dgvIAMaster, "Status")
            Me.prePareCheckToolEnable()
        End If
    End Function

#End Region

#Region " Events "

    Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click
        Dim SQL As String = String.Empty
        SQL += "select  VOUCHER_NO,e.ListB as MODE, d.ListA as Status , Document_NO, TOTAL_COST, AMOUNT, WHFROM, WHTO, Operator," + vbNewLine
        SQL += "RecDate,OperateDate, CheckedBy, CheckDate, UncheckedBy, UncheckedDate, REMARK" + vbNewLine
        SQL += "from  Sal_IAA a left join BSC_OtherDefineB d on a.Status=d.ListCode and d.ItemNo=16" + vbNewLine
        SQL += "left join BSC_OtherDefineB e on e.ItemNo=96 and a.Mode=e.listcode" + vbNewLine
        SQL += "  where 1=1 " + vbNewLine
        If TextLen(Me.tbxIANo1) > 0 Then
            SQL += " and a.VOUCHER_NO='" + safeText(Me.tbxIANo1) + "'" + vbNewLine
        End If
        If TextLen(Me.tbxOperator) > 0 Then
            SQL += " and a.Operator='" + safeText(Me.tbxOperator) + "'" + vbNewLine
        End If
        If Me.cbxFrom1.SelectedIndex <> -1 Then
            SQL += " and a.WHFROM='" + Me.cbxFrom1.SelectedValue.ToString + "'" + vbNewLine
        End If

        If Me.cbxTo1.SelectedIndex <> -1 Then
            SQL += " and a.WHTo='" + Me.cbxTo1.SelectedValue.ToString + "'" + vbNewLine
        End If
        If Me.cbxStatus.SelectedIndex <> -1 Then
            SQL += " and a.Status='" + Me.cbxStatus.SelectedValue.ToString + "'" + vbNewLine
        End If
        If Me.cbxMode.SelectedIndex <> -1 Then
            SQL += " and a.MODE='" + Me.cbxMode.SelectedValue.ToString + "'" + vbNewLine
        End If
        If Me.DateTimePicker2.Checked And Me.DateTimePicker3.Checked Then
            SQL += " and a.RecDate  between '" + Me.DateTimePicker2.Text + "' and '" + Me.DateTimePicker3.Text + "'" + vbNewLine
        ElseIf Me.DateTimePicker2.Checked Then
            SQL += " and a.RecDate='" + Me.DateTimePicker2.Text + "'"
        ElseIf Me.DateTimePicker3.Checked Then
            SQL += " and a.RecDate='" + Me.DateTimePicker3.Text + "'"
        End If
        Dim tb As DataTable = Exec(SQL, E_ExecType.DataTable)
        ' App.ExportToTxtForFormload(tb, Me.dgvIAMaster, "Tab_IAMaster", "master.txt")
        Me.dgvIAMaster.DataSource = tb
        SetDataGridViewBackColor(Me.dgvIAMaster, "Status")
        Me.SetToolEnable()
    End Sub

    Private Sub Frm_SALIA_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        PrepareCombox()
        prepareDGV()
    End Sub

    Private Sub dgvIAMaster_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvIAMaster.CellDoubleClick
        prePareCheckToolEnable()
        If e.RowIndex = -1 Then
            If Not Me.dgvIADetail.DataSource Is Nothing Then
                CType(Me.dgvIADetail.DataSource, DataTable).Rows.Clear()
            End If
            Exit Sub
        End If
        If Me.TabControl1.SelectedIndex <> 1 Then
            Me.TabControl1.SelectedIndex = 1
        End If
        'Dim mode As String = Me.dgvIAMaster.Rows(e.RowIndex).Cells("MODE").Value.ToString
        Dim Voucher_no As String = Me.dgvIAMaster.Rows(e.RowIndex).Cells("VOUCHER_NO").Value.ToString
        'Dim whFrom As String = Me.dgvIAMaster.Rows(e.RowIndex).Cells("WHFrom").Value.ToString
        'Dim whTo As String = Me.dgvIAMaster.Rows(e.RowIndex).Cells("WHTO").Value.ToString
        'Dim moperator As String = Me.dgvIAMaster.Rows(e.RowIndex).Cells("Operator").Value.ToString
        'Dim remark As String = Me.dgvIAMaster.Rows(e.RowIndex).Cells("Remark").Value.ToString
        'Dim OperateDate As String = Me.dgvIAMaster.Rows(e.RowIndex).Cells("OperateDate").Value.ToString

        'Me.tbxIANum2.Text = Voucher_no
        'Me.tbxMode2.Text = mode
        'Me.tbxTo2.Text = whTo
        'Me.tbxFrom2.Text = whFrom
        'Me.tbxRemark.Text = remark
        'Me.tbxOpDate2.Text = OperateDate
        'Me.tbxOperator2.Text = moperator
        'Me.txtStatus2.Text = Me.dgvIAMaster.Rows(e.RowIndex).Cells("Status").Value.ToString
        setText()
        Dim SQLStr As New System.Text.StringBuilder
        SQLStr.AppendLine("select ITEM_NO,SOSEQ_NO, Replace(b.BarCode,'*','') as BarCode,b.SupperItem,")
        SQLStr.AppendLine("b.Cnname,  WHFROM, WHTO, RECDATE, QTY, CURRENCY, COST, a.PRICE, AMOUNT")
        SQLStr.AppendLine("from Sal_IAB a left join BSC_Goods b on a.Item_NO=b.Enname")
        SQLStr.AppendLine("where a.Voucher_no='" + Voucher_no + "'")
        Dim tb As DataTable = Exec(SQLStr.ToString(), E_ExecType.DataTable)
        'App.ExportToTxtForFormload(tb, Me.dgvIADetail, "Tab_IADetail", "Detail.txt")
        Me.dgvIADetail.DataSource = tb

    End Sub

    Private Sub dgvIAMaster_Sorted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvIAMaster.Sorted
        SetDataGridViewBackColor(Me.dgvIAMaster, "Status")
    End Sub

    Private Sub dgvIAMaster_DataSourceChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvIAMaster.DataSourceChanged
        SetDataGridViewBackColor(Me.dgvIAMaster, "Status")
    End Sub

    Private Sub dgvIAMaster_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvIAMaster.CellValueChanged
        SetDataGridViewBackColor(Me.dgvIAMaster, "Status")
    End Sub

    Private Sub dgvIAMaster_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvIAMaster.CurrentCellChanged
        Me.prePareCheckToolEnable()
        If Me.TabControl1.SelectedIndex = 0 Then
            Dim dgv As DataGridView = CType(sender, DataGridView)
            If Not dgv.CurrentCell Is Nothing Then

                setText()
            Else
                Me.ClearText()
                If Me.dgvIADetail.DataSource Is Nothing Then
                    Exit Sub
                End If
                CType(Me.dgvIADetail.DataSource, DataTable).Rows.Clear()
                CType(Me.dgvIADetail.DataSource, DataTable).Rows.Clear()
            End If
        Else
            Dim dgv As DataGridView = CType(sender, DataGridView)
            If Not dgv.CurrentCell Is Nothing Then
                Dim colindex As Int32 = dgv.CurrentCell.ColumnIndex
                Dim rowIndex As Int32 = dgv.CurrentCell.RowIndex
                dgvIAMaster_CellDoubleClick(sender, New DataGridViewCellEventArgs(colindex, rowIndex))
            Else
                Me.ClearText()
                If Me.dgvIADetail.DataSource Is Nothing Then
                    Exit Sub
                End If
                CType(Me.dgvIADetail.DataSource, DataTable).Rows.Clear()
                CType(Me.dgvIADetail.DataSource, DataTable).Rows.Clear()
            End If
        End If
    End Sub

    Private Sub dgvIAMaster_RowsAdded(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles dgvIAMaster.RowsAdded
        SetDataGridViewBackColor(Me.dgvIAMaster, "Status")
    End Sub

#End Region

#Region " Methods "

    Private Sub PrepareCombox()
        Dim SQLStr As New System.Text.StringBuilder
        SQLStr.AppendLine("select  a.*,b.LIstA as DeptCode,b.ListB as Dept  from  bsc_storehouse a")
        SQLStr.AppendLine("inner join bsc_otherdefineB b on b.listb=a.fcode where itemNo='77'")
        Dim tb As DataTable = Exec(SQLStr.ToString(), E_ExecType.DataTable)
        Dim tb2 As DataTable = tb.Copy()
        Me.cbxFrom1.DisplayMember = "FShortName"
        Me.cbxFrom1.ValueMember = "Dept"
        Me.cbxFrom1.DataSource = tb
        Me.cbxTo1.DisplayMember = "FShortName"
        Me.cbxTo1.ValueMember = "Dept"
        Me.cbxTo1.DataSource = tb2

        '"|DeptCode|Dept|fShortName|"
        Me.DeptTb = tb2.Copy()

        Dim tb3 As DataTable = New DataTable()
        tb3.Columns.Add("VStatusName", GetType(String))
        tb3.Columns.Add("VStatusCode", GetType(String))
        tb3.AcceptChanges()
        Dim values As Array = System.Enum.GetValues(GetType(E_VouStatus))
        For i As Int32 = 0 To values.Length - 1
            Dim row As DataRow = tb3.NewRow
            row("VStatusCode") = System.Enum.Parse(GetType(E_VouStatusCode), values(i))
            row("VStatusName") = System.Enum.Parse(GetType(E_VouStatus), values(i))
            tb3.Rows.Add(row)
        Next
        Me.cbxStatus.DisplayMember = "VStatusName"
        Me.cbxStatus.ValueMember = "VStatusCode"
        Me.cbxStatus.DataSource = tb3
        Dim sql As String = "select listB as [SName],ListCode as [SValue] from BSC_OtherDefineB where itemno='96'"
        Dim tbmode As DataTable = Exec(sql, E_ExecType.DataTable)
        Me.cbxMode.DisplayMember = "SName"
        Me.cbxMode.ValueMember = "SValue"
        Me.cbxMode.DataSource = tbmode

        Me.cbxStatus.SelectedIndex = -1
        Me.cbxTo1.SelectedIndex = -1
        Me.cbxFrom1.SelectedIndex = -1
        Me.cbxMode.SelectedIndex = -1
    End Sub

    ''' <summary>
    '''“ 設置按鈕的Enable ”
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetToolEnable()
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            MainForm.ToolStripPrint.Enabled = True
            MainForm.ToolStripCheck.Enabled = False
            MainForm.ToolStripUnCheck.Enabled = False
            MainForm.ToolStripComplete.Enabled = False
            MainForm.ToolStripDelete.Enabled = False
            MainForm.ToolStripEdit.Enabled = False
            MainForm.ToolStripAdd.Enabled = False
            MainForm.ToolStripSave.Enabled = True
            MainForm.ToolStripCancel.Enabled = True
        ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            MainForm.ToolStripPrint.Enabled = True
            MainForm.ToolStripCheck.Enabled = False
            MainForm.ToolStripUnCheck.Enabled = False
            MainForm.ToolStripComplete.Enabled = False
            MainForm.ToolStripDelete.Enabled = False
            MainForm.ToolStripEdit.Enabled = False
            MainForm.ToolStripAdd.Enabled = False
            MainForm.ToolStripSave.Enabled = True
            MainForm.ToolStripCancel.Enabled = True
        ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
            MainForm.ToolStripPrint.Enabled = False
            MainForm.ToolStripCheck.Enabled = False
            MainForm.ToolStripUnCheck.Enabled = False
            MainForm.ToolStripComplete.Enabled = False
            MainForm.ToolStripDelete.Enabled = True
            MainForm.ToolStripEdit.Enabled = False
            MainForm.ToolStripAdd.Enabled = True
            MainForm.ToolStripSave.Enabled = False
            MainForm.ToolStripCancel.Enabled = False
        ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionPrint Then
            MainForm.ToolStripPrint.Enabled = True
            MainForm.ToolStripCheck.Enabled = False
            MainForm.ToolStripUnCheck.Enabled = False
            MainForm.ToolStripComplete.Enabled = False
            MainForm.ToolStripDelete.Enabled = False
            MainForm.ToolStripEdit.Enabled = False
            MainForm.ToolStripAdd.Enabled = False
            MainForm.ToolStripSave.Enabled = False
            MainForm.ToolStripCancel.Enabled = False
        End If

    End Sub

    Private Function setBillStatus(ByVal BillStatus As ModEnum.E_VouStatus) As Boolean
        Dim index As Int32 = dgvIAMaster.CurrentCell.RowIndex
        Dim IANum As String = Me.dgvIAMaster.Rows(index).Cells("VOUCHER_NO").Value.ToString
        Dim succed As Boolean = False
        Dim statusCode As String = System.Enum.GetName(GetType(E_VouStatusCode), Convert.ToInt32(BillStatus))


        Dim Str1 As String = String.Empty
        'Str1 += "update Sal_IAA set" + vbNewLine
        'Str1 += "status='{1}'," + vbNewLine
        'Str1 += "checkedby='{2}'" + vbNewLine
        'Str1 += "checkDate='{3}'" + vbNewLine
        'Str1 += "UncheckedBy='{2}'" + vbNewLine
        'Str1 += "UncheckedDate='{3}'" + vbNewLine
        'Str1 += "where voucher_no='{0}'" + vbNewLine
        Dim sqlstr As String = String.Empty

        Select Case BillStatus
            Case E_VouStatus.反核准
                Str1 += "update Sal_IAA set" + vbNewLine
                Str1 += "status='{1}'," + vbNewLine
                Str1 += "UncheckedBy='{2}'," + vbNewLine
                Str1 += "UncheckedDate=Convert(varchar(10),getdate(),21)" + vbNewLine
                Str1 += "where voucher_no='{0}'" + vbNewLine
                sqlstr = String.Format(Str1, IANum, statusCode, App.PubUserName)

            Case E_VouStatus.核准
                Dim sql As String = ""
                'If Me.CheckBox1.Checked Then
                '    sql = "Exec IAGoodsListCheck '" + IANum + "'"
                'Else
                sql = "Exec IAGoodsListCheck2 '" + IANum + "'"
                'End If
                Dim ds As DataSet = Exec(sql, E_ExecType.DataSet)
                Dim canotCheck As Boolean = False
                If ds.Tables.Count = 2 Then
                    Dim IAQty As Int32 = 0
                    Dim Enname As String = ""
                    For Each drow As DataRow In ds.Tables(0).Rows
                        IAQty = drow("Qty")
                        Enname = drow("Item_No")
                        If ds.Tables(1).Select("Enname='" + Enname + "' and IAAmount>=" + Convert.ToString(IAQty)).Length = 0 Then
                            canotCheck = True
                        End If
                    Next
                Else
                    canotCheck = True
                End If
                If canotCheck Then
                    succed = False
                    Return succed
                Else
                    Str1 += "update Sal_IAA set" + vbNewLine
                    Str1 += "status='{1}'," + vbNewLine
                    Str1 += "checkedby='{2}'," + vbNewLine
                    Str1 += "checkDate=Convert(varchar(10),getdate(),21)" + vbNewLine
                    Str1 += "where voucher_no='{0}'" + vbNewLine
                    sqlstr = String.Format(Str1, IANum, statusCode, App.PubUserName)
                End If

            Case E_VouStatus.保存
                Dim sql As String = "exec IAGoodsListCheck '" + IANum + "'"
                Dim ds As DataSet = Exec(sql, E_ExecType.DataSet)
                Dim canotsave As Boolean = False
                If ds.Tables.Count = 2 Then
                    Dim IAQty As Int32 = 0
                    Dim Enname As String = ""
                    For Each drow As DataRow In ds.Tables(0).Rows
                        IAQty = drow("Qty")
                        Enname = drow("Item_No")
                        If ds.Tables(1).Select("Enname='" + Enname + "' and IAAmount>=" + Convert.ToString(IAQty)).Length = 0 Then
                            canotsave = True
                        End If
                    Next
                Else
                    canotsave = True
                End If
                If canotsave Then
                    succed = False
                    Return succed
                Else
                    Str1 += "update Sal_IAA set" + vbNewLine
                    Str1 += "status='{1}'" + vbNewLine
                    Str1 += "where voucher_no='{0}'" + vbNewLine
                    sqlstr = String.Format(Str1, IANum, statusCode)
                End If

            Case E_VouStatus.作廢
                Str1 += "update Sal_IAA set" + vbNewLine
                Str1 += "status='{1}'" + vbNewLine
                Str1 += "where voucher_no='{0}'" + vbNewLine
                sqlstr = String.Format(Str1, IANum, statusCode)
            Case E_VouStatus.結案
                Str1 += "update Sal_IAA set" + vbNewLine
                Str1 += "status='{1}'" + vbNewLine
                Str1 += "where voucher_no='{0}'" + vbNewLine
                sqlstr = String.Format(Str1, IANum, statusCode)
        End Select

        Exec(sqlstr, E_ExecType.ExecuteNonQuery)

        Me.dgvIAMaster.Rows(index).Cells("Status").Value = BillStatus.ToString
        Select Case BillStatus
            Case E_VouStatus.核准
                Me.dgvIAMaster.Rows(index).Cells("checkedby").Value = App.PubUserName
                Me.dgvIAMaster.Rows(index).Cells("checkDate").Value = DateTime.Now.ToString("yyyy-MM-dd")
            Case E_VouStatus.反核准
                Me.dgvIAMaster.Rows(index).Cells("UncheckedBy").Value = App.PubUserName
                Me.dgvIAMaster.Rows(index).Cells("UncheckedDate").Value = DateTime.Now.ToString("yyyy-MM-dd")
        End Select

        Return True
    End Function

    ''' <summary>
    ''' 根據當前狀態判斷設置是否可以“核准”,“反核准”
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub prePareCheckToolEnable()
        If Me.dgvIAMaster.CurrentCell Is Nothing Then
            Me.MainForm.ToolStripCheck.Enabled = False
            Me.MainForm.ToolStripUnCheck.Enabled = False
            Exit Sub
        End If
        Dim IANum As String = Me.dgvIAMaster.Rows(Me.dgvIAMaster.CurrentCell.RowIndex).Cells("voucher_no").Value.ToString
        Dim status As String = Me.dgvIAMaster.Rows(Me.dgvIAMaster.CurrentCell.RowIndex).Cells("Status").Value.ToString

        Dim currentstatus As E_VouStatus = System.Enum.Parse(GetType(E_VouStatus), status)
        Select Case currentstatus
            Case E_VouStatus.保存
                Me.MainForm.ToolStripCheck.Enabled = True
                Me.MainForm.ToolStripUnCheck.Enabled = True
            Case E_VouStatus.核准
                Me.MainForm.ToolStripCheck.Enabled = False
                Me.MainForm.ToolStripUnCheck.Enabled = True
            Case E_VouStatus.反核准
                Me.MainForm.ToolStripCheck.Enabled = True
                Me.MainForm.ToolStripUnCheck.Enabled = False
        End Select
    End Sub

    Private Sub setText()
        Me.dtpRecDate2.Visible = False
        If Me.dgvIAMaster.CurrentCell Is Nothing Then
            Exit Sub
        End If

        For Each col As Control In Me.gbxIAInfo.Controls
            If col.GetType() Is GetType(TextBox) Or col.GetType Is GetType(RichTextBox) Then
                CType(col, TextBoxBase).ReadOnly = True
            End If
        Next

        Dim i As Int32 = Me.dgvIAMaster.CurrentCell.RowIndex
        Me.txtStatus2.Text = Me.dgvIAMaster.Rows(i).Cells("Status").Value.ToString
        Me.tbxTo2.Text = Me.dgvIAMaster.Rows(i).Cells("WHTO").Value.ToString
        Me.tbxOperator2.Text = Me.dgvIAMaster.Rows(i).Cells("Operator").Value.ToString
        Me.tbxFrom2.Text = Me.dgvIAMaster.Rows(i).Cells("WHFROM").Value.ToString
        Me.tbxRemark.Text = Me.dgvIAMaster.Rows(i).Cells("REMARK").Value.ToString
        Me.tbxMode2.Text = Me.dgvIAMaster.Rows(i).Cells("MODE").Value.ToString
        Me.tbxOpDate2.Text = Convert.ToDateTime(dgvIAMaster.Rows(i).Cells("RecDate").Value).ToShortDateString
        Me.tbxIANum2.Text = Me.dgvIAMaster.Rows(i).Cells("VOUCHER_NO").Value.ToString
    End Sub

    Private Sub ClearText()
        For Each col As Control In gbxIAInfo.Controls
            If col.GetType() Is GetType(TextBox) Or (col.GetType() Is GetType(RichTextBox)) Then
                col.Text = ""
            End If
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                Me.dtpRecDate2.Visible = True
            Else
                Me.dtpRecDate2.Visible = False
            End If
            Me.dtpRecDate2.Bounds = Me.tbxOpDate2.Bounds
            Me.dtpRecDate2.BringToFront()
        Next
    End Sub

    Private Sub prepareDGV()
        Dim Tab_IAMaster As New DataTable
        Tab_IAMaster.Columns.Add("VOUCHER_NO", GetType(String))
        Tab_IAMaster.Columns.Add("MODE", GetType(String))
        Tab_IAMaster.Columns.Add("Status", GetType(String))
        Tab_IAMaster.Columns.Add("Document_NO", GetType(String))
        Tab_IAMaster.Columns.Add("TOTAL_COST", GetType(Decimal))
        Tab_IAMaster.Columns.Add("AMOUNT", GetType(Decimal))
        Tab_IAMaster.Columns.Add("WHFROM", GetType(String))
        Tab_IAMaster.Columns.Add("WHTO", GetType(String))
        Tab_IAMaster.Columns.Add("Operator", GetType(String))
        Tab_IAMaster.Columns.Add("RecDate", GetType(DateTime))
        Tab_IAMaster.Columns.Add("OperateDate", GetType(String))
        Tab_IAMaster.Columns.Add("CheckedBy", GetType(String))
        Tab_IAMaster.Columns.Add("CheckDate", GetType(String))
        Tab_IAMaster.Columns.Add("UncheckedBy", GetType(String))
        Tab_IAMaster.Columns.Add("UncheckedDate", GetType(String))
        Tab_IAMaster.Columns.Add("REMARK", GetType(String))
        Tab_IAMaster.AcceptChanges()
        dgvIAMaster.DataSource = Tab_IAMaster
        Dim caption1 As String = "IA單號^VOUCHER_NO&模式^MODE&IA單狀態^Status&檔案編號^Document_NO&總成本^TOTAL_COST&總金額^AMOUNT&源倉庫^WHFROM&目的倉^WHTO&操作者^Operator&IA時間^RecDate&操作時間^OperateDate&核准者^CheckedBy&核准時間^CheckDate&反核准者^UncheckedBy&反核准時間^UncheckedDate&備注^REMARK"
        BindGridCaption(dgvIAMaster, BindHashTable(caption1))

        Dim Tab_IADetail As New DataTable
        Tab_IADetail.Columns.Add("ITEM_NO", GetType(String))
        Tab_IADetail.Columns.Add("SOSEQ_NO", GetType(Int16))
        Tab_IADetail.Columns.Add("BarCode", GetType(String))
        Tab_IADetail.Columns.Add("SupperItem", GetType(String))
        Tab_IADetail.Columns.Add("Cnname", GetType(String))
        Tab_IADetail.Columns.Add("WHFROM", GetType(Int16))
        Tab_IADetail.Columns.Add("WHTO", GetType(Int16))
        Tab_IADetail.Columns.Add("RECDATE", GetType(DateTime))
        Tab_IADetail.Columns.Add("QTY", GetType(Decimal))
        Tab_IADetail.Columns.Add("CURRENCY", GetType(String))
        Tab_IADetail.Columns.Add("COST", GetType(Double))
        Tab_IADetail.Columns.Add("PRICE", GetType(Decimal))
        Tab_IADetail.Columns.Add("AMOUNT", GetType(Decimal))
        Tab_IADetail.AcceptChanges()
        dgvIADetail.DataSource = Tab_IADetail
        Dim caption As String = "英文名^ITEM_NO&記錄序號^SOSEQ_NO&貨品條碼^BarCode&產商編號^SupperItem&貨品中文名^Cnname&源倉庫^WHFROM&目的倉^WHTO&IA時間^RECDATE&數量^QTY&貨幣種類^CURRENCY&成本價^COST&單價^PRICE&金額^AMOUNT"
        BindGridCaption(dgvIADetail, BindHashTable(caption))

    End Sub

    Private Sub InsertToDGV(ByRef dgv As DataGridView, ByVal table As DataTable)
        Dim dt As DataTable = CType(dgv.DataSource, DataTable)
        If Not dt Is Nothing Then
            For Each drow As DataRow In table.Rows
                Dim nrow As DataRow = dt.NewRow()
                For Each col As DataColumn In table.Columns
                    If dt.Columns.Contains(col.ColumnName) Then
                        nrow(col.ColumnName) = drow(col.ColumnName)
                    End If
                Next
                dt.Rows.Add(nrow)
            Next
            dt.AcceptChanges()
            dgv.DataSource = dt
        End If
    End Sub

    Private Sub dtpRecDate2_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpRecDate2.ValueChanged
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then

            For Each drow As DataGridViewRow In Me.dgvIADetail.Rows
                drow.Cells("RecDate").Value = dtpRecDate2.Text
            Next

        End If
    End Sub
#End Region


End Class
